<template>
  <div>
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        @input="inputFn"
        @search="searchFn"
        v-model="kw"
        v-fofo
      />
    </div>
    <!-- 搜索建议列表 -->
    <div class="sugg-list" v-if="this.kw.length > 0">
      <div
        class="sugg-item"
        v-for="(str, index) in suggestList"
        :key="index"
        @click="suggClickFn(str)"
        v-html="lightStr(str)"
      >
        搜索建议
      </div>
    </div>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="clearHistoryFn(str)"/>
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span
          class="history-item"
          v-for="(str, index) in historyList"
          :key="index"
          @click="historyItemFn"
        >
          {{ str }}</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import { suggestListAPI } from '@/api'
export default {
  data () {
    return {
      kw: '', // 搜索关键字
      timer: null, // 保存定时器
      suggestList: [], // 搜索建议列表
      historyList: JSON.parse(localStorage.getItem('history')) || [] // 搜索历史
    }
  },
  methods: {
    // 输入框改变
    inputFn (value) {
      // 输入框防抖---定时器n秒后再触发逻辑代码,如果函数再次触发,清空上一个定时器--好处:降低代码触发频率(节省性能和流量)
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (this.kw.length > 0) {
          const res = await suggestListAPI(this.kw)
          if (res.data.data.options[0] === null) {
            this.suggestList = []
          } else {
            this.suggestList = res.data.data.options
          }
        } else {
          // 输入框无值
          this.suggestList = []
        }
      }, 500)
    },
    // 输入框 - 搜索事件
    searchFn () {
      // 保存到本地
      this.historyList.push(this.kw)
      this.historyList = [...new Set(this.historyList)]
      setTimeout(() => {
        this.$router.push(`/search/${this.kw}`)
      }, 0)
    },
    // 联想菜单项 - 点击事件
    suggClickFn (str) {
      this.historyList.push(str)
      this.historyList = [...new Set(this.historyList)]
      setTimeout(() => {
        this.$router.push(`/search/${str}`)
      }, 0)
    },
    // 历史记录 - 点击跳转
    historyItemFn (str) {
      setTimeout(() => {
        this.$router.push(`/search/${str}`)
      }, 0)
    },
    // 处理高亮字符
    lightStr (targetStr) {
      const reg = new RegExp(this.kw, 'ig')
      return targetStr.replace(reg, (substring) => {
        // substring: 正则匹配到要被替换的"字符"
        // d或者D
        return `<span style="color: red;">${substring}</span>`
      })
    },
    // 清空历史记录
    clearHistoryFn () {
      this.historyList = []
    }
  },
  watch: {
    historyList () {
      localStorage.setItem('history', JSON.stringify(this.historyList))
    }
  }
}
</script>

<style scoped lang="less">
.search-header {
  height: 46px;
  display: flex;
  align-items: center;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>
